package com.qiuhu.designerpattern.singleton;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试单例模式
 * 
 * @author Administrator
 *
 */
public class TestSingleton {

	boolean lock;

	public boolean isLock() {
		return lock;
	}

	public void setLock(boolean lock) {
		this.lock = lock;
	}

	public static void main(String[] args) throws InterruptedException {

		final Set<String> instanceSet = Collections.synchronizedSet(new HashSet<String>());
		// final TestSingleton lock = new TestSingleton();
		final CountDownLatch cdl = new CountDownLatch(1);
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i < 100; i++) {
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					try {
						cdl.await();
//						Singleton singleton = Singleton.getInstance();  //test??
						//333test2 test
						SychronizedSingleton singleton = SychronizedSingleton.getInstance();
						instanceSet.add(singleton.toString());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			});
		}
		Thread.sleep(1000);
		cdl.countDown();
		Thread.sleep(1000);
		System.out.println("一共有" + instanceSet.size() + "个实例");
		for (String instance : instanceSet) {
			System.out.println(instance);
		}
		executorService.shutdown();
	}
}
